package persentation.presentAdministrator;

import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import org.omg.CORBA.PUBLIC_MEMBER;
import org.omg.PortableServer.ID_ASSIGNMENT_POLICY_ID;

import businesslogic.courseBl.CourseController;
import businesslogic.userBl.AdministratorController;
import businesslogic.userBl.DepartmentDean;
import persentation.presentLogin.LoginFrame;
import po.coursePO.CoursePO;
import po.userPO.DepartmentDeanPO;
import po.userPO.StudentPO;
import po.userPO.TeacherPO;
import po.userPO.UniversityDeanPO;
import po.userPO.UserPO;
import vo.teachPlanVO.TeachPlanVO;
import vo.userVO.DepartmentDeanVO;
import vo.userVO.StudentVO;
import vo.userVO.TeacherVO;
import vo.userVO.UniversityDeanVO;
import vo.userVO.UserVO;
import dataservice.ResultMessage;

public class AddUserPanel extends JPanel{
	private JTable table;
	private JTable studentTable;
	private JScrollPane scrollPane;
	private DefaultTableModel model;
	private DefaultTableModel studentModel;
	private ShowUserPanel showUserPanel;
	private JButton okButton;
	private JButton button_2;
	private JComboBox<String> selectBox;
	private JComboBox<String> departmentBox;
	private int userType;
	private int num=0;
	private int studentNum=0;
	private String departmentID=null;
	private String []departmentList=new String[28];
	private CourseController courseController;
	private JButton button;
	
	private final Integer[] grades={1,2,3,4};
	private JComboBox<Integer> gradeBox;
	private ArrayList<ResultMessage> resultMessageList=new ArrayList<>();
	
	private AdministratorController administratorController=new AdministratorController();
	
	
	
	public AddUserPanel(CourseController courseController){
		setSize(800,600);
		setLayout(null);
		final DefaultCellEditor stringEditor=new DefaultCellEditor(new JTextField());

		
		ArrayList<String> departmentArrayList;
		try {
			departmentArrayList = courseController.getAllDepartments();
			for (int i = 0; i<departmentArrayList.size(); i++) {
				departmentList[i]=departmentArrayList.get(i);
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
//			new ExceptionHandler(this,new LoginFrame()).networkException();
		}
		
		
		
		
		
		selectBox=new JComboBox<String>();
		selectBox.addItemListener(new ItemListener() {
			
			@Override
			public void itemStateChanged(ItemEvent e) {
				if(e.getStateChange()==ItemEvent.SELECTED)
					userType=selectBox.getSelectedIndex();
					showTable();
			}
		});
		
		
		
		
		selectBox.setBounds(190, 30, 177, 30);
		selectBox.setModel(new DefaultComboBoxModel<String>(new String[]{"学生","任课教师","院系教务老师","教务处老师"}));
		selectBox.setFont(new Font("微软雅黑",Font.PLAIN,20));
		add(selectBox);
		
		model=new DefaultTableModel(new Object[][] {}, new String[] { "用户ID",
				"用户姓名",  "初始密码" });
		table=new JTable(model){
			 public TableCellEditor getCellEditor(int row, int column)
	            {
	               
						return stringEditor;
					
	            } 
		};
		table.getTableHeader().setReorderingAllowed(false);
		table.getTableHeader().setResizingAllowed(false);
		
		TableColumn tc = table.getColumnModel().getColumn(2);
		scrollPane = new JScrollPane();
		scrollPane.setBounds(37, 93, 712, 384);
		
		gradeBox=new JComboBox(grades);
		final DefaultCellEditor gradeEditor=new DefaultCellEditor(gradeBox);
		
		studentModel=new DefaultTableModel(new Object[][] {}, new String[] { "用户ID",
				"用户姓名", "年级", "初始密码" });
		
		studentTable=new JTable(studentModel){
			 public TableCellEditor getCellEditor(int row, int column)
	            {
	                int modelColumn = convertColumnIndexToModel( column );

	                if (modelColumn == 2)
	                    return (TableCellEditor) gradeEditor;
	                else {
						return stringEditor;
					}
	            } 
		};
		studentTable.addMouseListener(new MouseListener() {
			
			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mousePressed(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void mouseClicked(MouseEvent e) {
				button_2.setEnabled(true);
				
				
			}
		});
		studentTable.getTableHeader().setReorderingAllowed(false);
		studentTable.getTableHeader().setResizingAllowed(false);
		
		TableColumn tc1 = studentTable.getColumnModel().getColumn(2);
//		tc.setCellEditor(table.getDefaultEditor(Boolean.class));
//		tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
//		scrollPane = new JScrollPane();
//		scrollPane.setBounds(37, 93, 712, 384);
		
		showTable();
		
		
		
		
		JLabel label = new JLabel("新增用户类型");
		label.setBounds(48, 26, 127, 38);
		label.setFont(new Font("微软雅黑", Font.PLAIN, 20));
		add(label);
		
		add(scrollPane);
		
		button = new JButton("确认");
		button.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				int m=JOptionPane.showConfirmDialog(null,"确认添加用户？","确认",JOptionPane.YES_NO_OPTION);
				if(m==JOptionPane.YES_OPTION){
					

					switch (userType) {
					case 0:
						for(int i=0;i<studentNum;i++)
							if(studentTable.getValueAt(i, 0)==null||studentTable.getValueAt(i, 1)==null
							||studentTable.getValueAt(i,2)==null)
							{
								studentModel.removeRow(i);
								studentTable.setModel(studentModel);
								studentNum--;
							}
					
						
						break;

					default:
						
						for(int i=0;i<num;i++)
							if(table.getValueAt(i, 0)==null||table.getValueAt(i, 1)==null)
							{
								model.removeRow(i);
								table.setModel(model);
								num--;
							}
						break;
					}
					
					ResultMessage message=sendRequest();
					System.out.println(message+"jdakldnafasfafafsdafasfasdfsafsa");
					System.out.println(message==ResultMessage.UPDATE_SUCCESS);
					if(message==ResultMessage.INSERT_SUCCESS){
						button.setEnabled(false);
						
						JOptionPane.showMessageDialog(null,"新用户添加成功！","提示",JOptionPane.INFORMATION_MESSAGE);
						showUserPanel.fillTable();
						model = (DefaultTableModel) table.getModel();
						
						switch (userType) {
						case 0:
							for(int i=studentNum;i>0;i--)
								studentModel.removeRow(i-1);
							
							studentNum=0;
							
							break;

						default:
							for(int i=num;i>0;i--)
								model.removeRow(i-1);
							
							num=0;
							break;
						}
						
						
						
						
						
					}else{
						JOptionPane.showMessageDialog(null,"新用户添加失败,请核对您填写的信息！","提示",JOptionPane.INFORMATION_MESSAGE);
					}
				}
				
				
				
				
				
			}
		});
		button.setEnabled(false);
		button.setFont(new Font("微软雅黑", Font.PLAIN, 20));
		button.setBounds(94, 487, 93, 38);
		add(button);
		
		okButton=new JButton("添加");
		okButton.setBounds(251, 487, 82, 38);
		okButton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				
				addRow();
				
			}
		});
		okButton.setFont(new Font("微软雅黑",Font.PLAIN,20));
		add(okButton);
		
		JLabel label_1 = new JLabel("所在院系");
		label_1.setFont(new Font("微软雅黑", Font.PLAIN, 20));
		label_1.setBounds(423, 26, 87, 38);
		add(label_1);
		
		departmentBox = new JComboBox<String>();
		departmentBox.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				if (e.getStateChange()==ItemEvent.SELECTED) {
					departmentID=departmentBox.getSelectedItem().toString();
					showTable();
				}
			}
		});
		
		departmentBox.setFont(new Font("微软雅黑", Font.PLAIN, 20));
		departmentBox.setBounds(542, 30, 177, 30);
		departmentBox.setModel(new DefaultComboBoxModel(departmentList));
		add(departmentBox);
		
		JButton button_1 = new JButton("导入");
		button_1.addActionListener(new  ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				final JFileChooser jFileChooser=new JFileChooser();
				
				jFileChooser.setFileFilter(new FileFilter() {
					
					@Override
					public String getDescription() {
						// TODO Auto-generated method stub
						return null;
					}
					
					@Override
					public boolean accept(File f) {
						return f.getName().endsWith(".xls");
					}
				});
				
				int retVal=jFileChooser.showOpenDialog(null);
				jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				if(retVal==JFileChooser.APPROVE_OPTION){
					
					
					File file=jFileChooser.getSelectedFile();
				
					
						try {
							Workbook workbook=Workbook.getWorkbook(file);
							Sheet sheet=workbook.getSheet(0);
							int row=sheet.getRows();
							switch (userType) {
							case 0:
								for(int i=0;i<row;i++){
									
									String id,name,password;
									int grade;
									Cell idCell=sheet.getCell(0,i);
									Cell nameCell=sheet.getCell(1,i );
									Cell passwordCell=sheet.getCell(3,i);
									Cell gradecCell=sheet.getCell(2,1);
									id=idCell.getContents().toString();
									name=nameCell.getContents().toString();
									grade=Integer.parseInt(gradecCell.getContents().toString());
									password=passwordCell.getContents().toString();
									studentModel = (DefaultTableModel) studentTable.getModel();
									Object[] data = new Object[4];
									data[0]=id;
									data[1]=name;
									data[2]=grade;
									data[3]=password;
									studentModel.addRow(data);
									studentNum++;
									
									
									
									button.setEnabled(true);
								
							}
								break;

							default:
								for(int i=0;i<row;i++){
									
									String id,name,password;
									Cell idCell=sheet.getCell(0,i);
									Cell nameCell=sheet.getCell(1,i );
									Cell passwordCell=sheet.getCell(2,i);
									id=idCell.getContents().toString();
									name=nameCell.getContents().toString();
									password=passwordCell.getContents().toString();
									model = (DefaultTableModel) table.getModel();
									Object[] data = new Object[3];
									data[0]=id;
									data[1]=name;
									data[2]=password;
									model.addRow(data);
									num++;
									
									
									
									button.setEnabled(true);
								
							}
								break;
							}
							
							workbook.close();	
						} catch (BiffException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
				
				}
			}
		});
		button_1.setFont(new Font("微软雅黑", Font.PLAIN, 20));
		button_1.setBounds(546, 487, 82, 38);
		add(button_1);
		button_2 = new JButton("删除");
		button_2.setEnabled(false);
		button_2.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				deleteRow();
				switch (userType) {
				case 0:
					if(studentTable.getRowCount()==0)
						setEnabled(false);
					
					break;

				default:
					if(table.getRowCount()==0)
						setEnabled(false);
					break;
				}
			}
		});
		button_2.setFont(new Font("微软雅黑", Font.PLAIN, 20));
		button_2.setBounds(405, 487, 82, 38);
		add(button_2);
		
		
		setVisible(true);
		
		
	
	
		
		
		
		
		
	}
	
	
	public void showTable(){
		switch (userType) {
		case 0:
			
			scrollPane.setViewportView(studentTable);
			break;

		default:
			scrollPane.setViewportView(table);
			break;
		}
	}
	
	
	
	
	public ResultMessage sendRequest(){
		
		
		ResultMessage msg=null;
		resultMessageList.clear();
		
		
		if(userType==0){
			
			
			for(int i=0;i<studentNum;i++){
				if(studentTable.getValueAt(i, 0).toString()==" "||studentTable.getValueAt(i, 1).toString()==" "||
						studentTable.getValueAt(i, 2).toString()==" ")
					continue;
				
				ResultMessage message = null;
				
				
				StudentVO studentVO=new StudentVO(studentTable.getValueAt(i, 0).toString().trim(), studentTable.getValueAt(i, 1).toString().trim(), departmentID, Integer.parseInt(studentTable.getValueAt(i, 2).toString().trim()));
				
				try {
					message=administratorController.addUser(studentVO);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					e1.printStackTrace();
					ExceptionHandler.networkException();
				}
				if(studentTable.getValueAt(i, 3).toString().trim().length()>=6&&studentTable.getValueAt(i, 3).toString().trim().length()<=12){
					try {
						administratorController.modifyPassword(studentTable.getValueAt(i, 0).toString().trim(), studentTable.getValueAt(i, 3).toString().trim());
					
						
						
						System.out.println(studentTable.getValueAt(i, 3).toString());
						
					
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						ExceptionHandler.networkException();
					}
				}
					
				
				resultMessageList.add(message);
			}
		}
		for(int i=0;i<num;i++){
			
			if(table.getValueAt(i, 0).toString()==" "||table.getValueAt(i, 1).toString()==" ")
				continue;
			ResultMessage message = null;
			
			switch (userType) {


			case 1:
				TeacherVO teacherVO=new TeacherVO(table.getValueAt(i, 0).toString().trim(),table.getValueAt(i, 1).toString().trim() ,departmentID);
				
				
				try {
					message=administratorController.addUser(teacherVO);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					ExceptionHandler.networkException();
				}
				
				if(table.getValueAt(i, 2).toString().trim().length()>=6&&table.getValueAt(i, 2).toString().trim().length()<=12)
					try {
						administratorController.modifyPassword(table.getValueAt(i, 0).toString().trim(), table.getValueAt(i, 2).toString().trim());

						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						ExceptionHandler.networkException();
					}
				
				break;
			case 2:
				
				DepartmentDeanVO departmentDeanVO=new DepartmentDeanVO(table.getValueAt(i, 0).toString().trim(), table.getValueAt(i, 1).toString().trim(), departmentID);

				try {
					message=administratorController.addUser(departmentDeanVO);
					if(table.getValueAt(i, 2).toString().trim().length()>=6&&table.getValueAt(i, 2).toString().trim().length()<=12)
						
						administratorController.modifyPassword(table.getValueAt(i, 0).toString().trim(), table.getValueAt(i, 2).toString().trim());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					ExceptionHandler.networkException();
				}
				
				break;
			case 3:
				UniversityDeanVO universityDeanVO=new UniversityDeanVO(table.getValueAt(i, 0).toString().trim(),table.getValueAt(i, 1).toString().trim());
				
				try {
					message=administratorController.addUser(universityDeanVO);
					if(table.getValueAt(i, 2).toString().trim().length()>=6&&table.getValueAt(i, 2).toString().trim().length()<=12)
						
						administratorController.modifyPassword(table.getValueAt(i, 0).toString().trim(), table.getValueAt(i, 2).toString().trim());
					System.out.println("name： "+table.getValueAt(i, 1).toString());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					ExceptionHandler.networkException();
				}
				
				break;
				
				
			}
			
			
			
			resultMessageList.add(message);
			
		
		
		
		}
		for(ResultMessage m:resultMessageList){
			if(m!=ResultMessage.INSERT_SUCCESS)
				msg=ResultMessage.INSERT_FAILURE;
			else {
				msg=ResultMessage.INSERT_SUCCESS;
			}
		}
		
		
		
		return msg;
	}
	
	
	public void deleteRow(){
		
		switch (userType) {
		case 0:
			if(studentTable.getSelectedRow()==-1)
				return;
			studentModel = (DefaultTableModel) studentTable.getModel();
			studentModel.removeRow(studentTable.getSelectedRow());
			studentNum--;
			
			studentTable.setModel(studentModel);
			break;

		default:
			if(table.getSelectedRow()==-1)
				return;
			model = (DefaultTableModel) table.getModel();
			model.removeRow(table.getSelectedRow());
			num--;
			table.setModel(model);
			break;
		}
	}
	public void addRow(){
		Object[] data ;
		switch (userType) {
		case 0:
			studentModel = (DefaultTableModel) studentTable.getModel();
			data = new Object[4];
			data[0] = " ";
			data[1] = " ";
			data[2] = " ";
			data[3] = " ";
		
			
			studentNum++;
			
			
			studentModel.addRow(data);
			button.setEnabled(true);
			
			studentTable.setModel(studentModel);
			
			break;

		default:
			model = (DefaultTableModel) table.getModel();
			data = new Object[3];
			data[0] = " ";
			data[1] = " ";
			data[2] = " ";
		
			
			num++;
			
			System.out.println(num);
			model.addRow(data);
			button.setEnabled(true);
			
			table.setModel(model);
			break;
		}
	}
	
	public void setShowPanel(ShowUserPanel showUserPanel){
		this.showUserPanel=showUserPanel;
	}


}
